package com.nowcoder;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;

public class TrainPullIn {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            int n = scanner.nextInt();
            int[] arr = new int[n];
            for (int i = 0; i < n; i++) {
                arr[i] = scanner.nextInt();
            }
            // 打印输出出站方案
            solver(arr);
        }
    }

    public static void solver(int[] arr) {
        // 将火车入站的编号，按照从小到大的顺序排序
        int[] sortedPull = arr.clone();
        Arrays.sort(sortedPull);
        int len = arr.length;
        int[] tempArr = new int[len];
        boolean[] visited = new boolean[len + 1];
        dfs(0, len, tempArr, visited, sortedPull, arr);
    }

    /**
     * 使用深度优先搜索实现，从小到大大全排列出站顺序
     */
    private static void dfs(int x, int n,
                            int[] tempArr, boolean[] visited,
                            int[] sortedPull, int[] arr) {
        if (n == x) {
            if (check(tempArr, arr)) {
                for (int i = 0; i < n - 1; i++) {
                    System.out.print(tempArr[i] + " ");
                }
                System.out.println(tempArr[n - 1]);
            }
        }
        for (int i = 0; i < n; i++) {
            int y = sortedPull[i];
            if (!visited[y]) {
                visited[y] = true;
                tempArr[x] = y;
                dfs(x + 1, n, tempArr, visited, sortedPull, arr);
                visited[y] = false;
            }
        }
    }

    /**
     * 判断出站序列是否是正确的出站顺序
     *
     * @param tempArr
     * @return
     */
    private static boolean check(int[] tempArr, int[] arr) {
        LinkedList<Integer> stack = new LinkedList<>();
        int len = arr.length;
        int j = 0;
        for (int i = 0; i < len; i++) {
            // 进站顺序压栈
            stack.push(arr[i]);
            while (!stack.isEmpty() && stack.peek() == tempArr[j]) {
                j++;
                stack.pop();
            }
        }
        return stack.isEmpty();
    }
}
